<template>
  <div class="tracking-container">
    <div class="page-header">
      <h2 class="page-title">进度跟踪</h2>
      <div class="summary-stats">
        <div class="stat-item">
          <span class="stat-value">{{ projects.length }}</span>
          <span class="stat-label">进行中项目</span>
        </div>
        <div class="stat-item">
          <span class="stat-value warning">{{ delayedTasks.length }}</span>
          <span class="stat-label">延期任务</span>
        </div>
        <div class="stat-item">
          <span class="stat-value danger">{{ warnings.filter(w => w.status !== 'processed').length }}</span>
          <span class="stat-label">预警信息</span>
        </div>
      </div>
    </div>

    <el-row :gutter="20">
      <el-col :span="16">
        <el-card class="card">
          <template #header>
            <div class="card-header">
              <div class="header-title">
                <el-icon><TrendCharts /></el-icon>
                <span>项目进度趋势</span>
              </div>
              <div class="header-actions">
                <el-select v-model="selectedProject" placeholder="选择项目" class="filter-select">
                  <el-option label="全部项目" value="" />
                  <el-option
                    v-for="project in projects"
                    :key="project.id"
                    :label="project.name"
                    :value="project.id"
                  />
                </el-select>
                <el-select v-model="timeRange" placeholder="时间范围" class="filter-select">
                  <el-option label="本周" value="week" />
                  <el-option label="本月" value="month" />
                  <el-option label="本季度" value="quarter" />
                </el-select>
              </div>
            </div>
          </template>
          <div class="chart-container">
            <div ref="progressChart" style="width: 100%; height: 360px"></div>
          </div>
        </el-card>

        <el-row :gutter="20" class="mt-20">
          <el-col :span="12">
            <el-card class="card">
              <template #header>
                <div class="card-header">
                  <div class="header-title">
                    <el-icon><Odometer /></el-icon>
                    <span>项目进度</span>
                  </div>
                </div>
              </template>
              
              <el-scrollbar height="260px">
                <div class="project-list">
                  <div 
                    v-for="project in projects" 
                    :key="project.id" 
                    class="project-item"
                    :class="{ 'project-selected': selectedProject === project.id.toString() }"
                    @click="selectProject(project.id)"
                  >
                    <div class="project-info">
                      <div class="project-name">{{ project.name }}</div>
                      <div class="project-meta">
                        <span>负责人: {{ project.manager }}</span>
                        <span>截止日期: {{ project.deadline }}</span>
                      </div>
                    </div>
                    <div class="project-progress">
                      <div class="progress-header">
                        <span>计划进度: {{ project.planProgress }}%</span>
                        <span :class="getProgressClass(project.progress, project.planProgress)">
                          实际进度: {{ project.progress }}%
                        </span>
                      </div>
                      <el-progress 
                        :percentage="project.progress" 
                        :status="getProgressStatus(project.progress, project.planProgress)"
                        :stroke-width="10"
                      />
                    </div>
                  </div>
                </div>
              </el-scrollbar>
            </el-card>
          </el-col>
          
          <el-col :span="12">
            <el-card class="card">
              <template #header>
                <div class="card-header">
                  <div class="header-title">
                    <el-icon><SetUp /></el-icon>
                    <span>资源使用情况</span>
                  </div>
                </div>
              </template>
              
              <el-scrollbar height="260px">
                <div class="resource-list">
                  <div v-for="resource in resources" :key="resource.id" class="resource-item">
                    <div class="resource-header">
                      <div class="resource-title">
                        <span class="resource-name">{{ resource.name }}</span>
                        <el-tag 
                          size="small" 
                          :type="getResourceTagType(resource.usage)" 
                          effect="light"
                        >
                          {{ resource.status }}
                        </el-tag>
                      </div>
                      <span class="resource-usage">{{ resource.usage }}%</span>
                    </div>
                    <el-progress
                      :percentage="resource.usage"
                      :status="getResourceStatus(resource.usage)"
                      :stroke-width="10"
                    />
                  </div>
                </div>
              </el-scrollbar>
            </el-card>
          </el-col>
        </el-row>
      </el-col>
      
      <el-col :span="8">
        <el-card class="card">
          <template #header>
            <div class="card-header">
              <div class="header-title">
                <el-icon><Warning /></el-icon>
                <span>预警信息</span>
              </div>
              <el-tag type="danger" effect="dark" size="small">
                {{ warnings.filter(w => w.status !== 'processed').length }}条
              </el-tag>
            </div>
          </template>
          
          <el-scrollbar height="280px">
            <div class="warning-list">
              <el-empty v-if="warnings.length === 0" description="暂无预警信息" />
              
              <el-timeline v-else>
                <el-timeline-item
                  v-for="warning in warnings"
                  :key="warning.id"
                  :type="warning.type"
                  :timestamp="warning.time"
                  :hollow="warning.status === 'processed'"
                >
                  <div class="warning-item" :class="{ 'warning-processed': warning.status === 'processed' }">
                    <div class="warning-header">
                      <h4>{{ warning.title }}</h4>
                      <el-tag 
                        v-if="warning.status === 'processed'" 
                        type="success" 
                        size="small"
                        effect="light"
                      >
                        已处理
                      </el-tag>
                    </div>
                    <p class="warning-content">{{ warning.content }}</p>
                    <div class="warning-actions" v-if="warning.status !== 'processed'">
                      <el-button type="primary" size="small" @click="processWarning(warning.id)">处理</el-button>
                      <el-button type="info" size="small" plain @click="ignoreWarning(warning.id)">忽略</el-button>
                    </div>
                  </div>
                </el-timeline-item>
              </el-timeline>
            </div>
          </el-scrollbar>
        </el-card>
        
        <el-card class="card mt-20">
          <template #header>
            <div class="card-header">
              <div class="header-title">
                <el-icon><AlarmClock /></el-icon>
                <span>延期任务</span>
              </div>
              <el-button type="primary" text>查看全部</el-button>
            </div>
          </template>
          
          <div class="delayed-tasks">
            <el-empty v-if="delayedTasks.length === 0" description="暂无延期任务" />
            
            <el-table 
              v-else
              :data="delayedTasks" 
              style="width: 100%" 
              border
              size="small"
              :header-cell-style="{ backgroundColor: '#f5f7fa' }"
            >
              <el-table-column prop="name" label="任务名称" min-width="120" show-overflow-tooltip />
              <el-table-column prop="project" label="所属项目" width="120" show-overflow-tooltip />
              <el-table-column label="负责人" width="80" align="center">
                <template #default="{ row }">
                  <el-tooltip :content="row.manager" placement="top">
                    <el-avatar :size="24" :src="getAvatarUrl(row.manager)"></el-avatar>
                  </el-tooltip>
                </template>
              </el-table-column>
              <el-table-column prop="delayDays" label="延期天数" width="100" align="center">
                <template #default="{ row }">
                  <el-tag 
                    :type="getDelayTagType(row.delayDays)" 
                    effect="plain"
                    size="small"
                  >
                    {{ row.delayDays }}天
                  </el-tag>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch, onBeforeUnmount } from 'vue'
import * as echarts from 'echarts'
import { 
  TrendCharts, Warning, AlarmClock, SetUp, Odometer 
} from '@element-plus/icons-vue'

const timeRange = ref('week')
const selectedProject = ref('')
const progressChart = ref(null)
let chartInstance = null

const projects = reactive([
  {
    id: 1,
    name: '变电站电气安装工程',
    manager: '张三',
    deadline: '2024-05-30',
    progress: 60,
    planProgress: 75,
    status: 'active'
  },
  {
    id: 2,
    name: '配电室改造项目',
    manager: '李四',
    deadline: '2024-04-20',
    progress: 35,
    planProgress: 50,
    status: 'active'
  },
  {
    id: 3,
    name: '生产线电气升级',
    manager: '王五',
    deadline: '2024-03-15',
    progress: 80,
    planProgress: 90,
    status: 'active'
  }
])

const warnings = reactive([
  {
    id: 1,
    title: '主变压器安装进度滞后',
    content: '原定于2月15日完成的主变压器安装，目前进度仅完成60%',
    time: '2024-02-20 10:00',
    type: 'danger',
    status: 'new',
    projectId: 1
  },
  {
    id: 2,
    title: '配电柜安装材料不足',
    content: '配电柜安装所需材料库存不足，请及时补充',
    time: '2024-02-19 14:30',
    type: 'warning',
    status: 'new',
    projectId: 2
  },
  {
    id: 3,
    title: '控制系统调试人员不足',
    content: '控制系统调试阶段需要增加2名技术人员',
    time: '2024-02-18 16:00',
    type: 'warning',
    status: 'processed',
    projectId: 3
  },
  {
    id: 4,
    title: '设备验收文档不完整',
    content: '设备验收文档缺少重要参数记录，需补充完善',
    time: '2024-02-16 09:15',
    type: 'info',
    status: 'new',
    projectId: 1
  }
])

const delayedTasks = reactive([
  {
    id: 1,
    name: '主变压器安装',
    project: '变电站电气安装工程',
    manager: '张三',
    deadline: '2024-02-15',
    delayDays: 5,
    projectId: 1
  },
  {
    id: 2,
    name: '配电柜安装',
    project: '配电室改造项目',
    manager: '李四',
    deadline: '2024-02-20',
    delayDays: 3,
    projectId: 2
  },
  {
    id: 3,
    name: '控制线路布置',
    project: '生产线电气升级',
    manager: '王五',
    deadline: '2024-02-18',
    delayDays: 2,
    projectId: 3
  }
])

const resources = reactive([
  {
    id: 1,
    name: '技术人员',
    status: '紧张',
    usage: 85
  },
  {
    id: 2,
    name: '施工设备',
    status: '充足',
    usage: 45
  },
  {
    id: 3,
    name: '材料库存',
    status: '不足',
    usage: 90
  },
  {
    id: 4,
    name: '资金使用',
    status: '正常',
    usage: 60
  }
])

const getProgressStatus = (progress, plan) => {
  if (progress >= plan) return 'success'
  if (progress >= plan * 0.8) return 'warning'
  return 'exception'
}

const getProgressClass = (progress, plan) => {
  if (progress >= plan) return 'text-success'
  if (progress >= plan * 0.8) return 'text-warning'
  return 'text-danger'
}

const getResourceStatus = (usage) => {
  if (usage >= 80) return 'exception'
  if (usage >= 50) return 'warning'
  return 'success'
}

const getResourceTagType = (usage) => {
  if (usage >= 80) return 'danger'
  if (usage >= 50) return 'warning'
  return 'success'
}

const getDelayTagType = (days) => {
  if (days > 5) return 'danger'
  if (days > 2) return 'warning'
  return 'info'
}

const getAvatarUrl = (name) => {
  return 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
}

const processWarning = (id) => {
  const index = warnings.findIndex(w => w.id === id)
  if (index !== -1) {
    warnings[index].status = 'processed'
  }
}

const ignoreWarning = (id) => {
  const index = warnings.findIndex(w => w.id === id)
  if (index !== -1) {
    warnings.splice(index, 1)
  }
}

const selectProject = (id) => {
  selectedProject.value = selectedProject.value === id.toString() ? '' : id.toString()
}

const getChartData = (timeType, projectId) => {
  const timeData = {
    week: {
      xAxis: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
      plan: [15, 30, 45, 60, 75, 85, 100],
      actual: [10, 25, 40, 52, 60, 70, 85]
    },
    month: {
      xAxis: ['第1周', '第2周', '第3周', '第4周'],
      plan: [25, 50, 75, 100],
      actual: [20, 40, 60, 80]
    },
    quarter: {
      xAxis: ['1月', '2月', '3月'],
      plan: [30, 60, 100],
      actual: [25, 50, 85]
    }
  }
  
  if (projectId) {
    const projectIndex = projects.findIndex(p => p.id === parseInt(projectId))
    if (projectIndex !== -1) {
      const offset = (projectIndex + 1) * 5
      return {
        xAxis: timeData[timeType].xAxis,
        plan: timeData[timeType].plan,
        actual: timeData[timeType].actual.map(val => Math.max(0, val - offset))
      }
    }
  }
  
  return timeData[timeType]
}

const initChart = () => {
  if (chartInstance) {
    chartInstance.dispose()
  }
  
  chartInstance = echarts.init(progressChart.value)
  updateChart()
}

const updateChart = () => {
  if (!chartInstance) return
  
  const data = getChartData(timeRange.value, selectedProject.value)
  
  const option = {
    color: ['#409EFF', '#67C23A'],
    grid: {
      top: 60,
      left: '3%',
      right: '4%',
      bottom: 60,
      containLabel: true
    },
    title: {
      text: '项目进度趋势图',
      left: 'center',
      top: 10
    },
    tooltip: {
      trigger: 'axis',
      formatter: function(params) {
        const planValue = params[0].value
        const actualValue = params[1].value
        const difference = actualValue - planValue
        const diffText = difference >= 0 
          ? `<span style="color:#67C23A">+${difference}%</span>` 
          : `<span style="color:#F56C6C">${difference}%</span>`
        
        return `${params[0].axisValue}<br/>
                ${params[0].marker} ${params[0].seriesName}: ${planValue}%<br/>
                ${params[1].marker} ${params[1].seriesName}: ${actualValue}%<br/>
                差异: ${diffText}`
      }
    },
    legend: {
      data: ['计划进度', '实际进度'],
      bottom: 10
    },
    xAxis: {
      type: 'category',
      data: data.xAxis,
      axisLine: {
        lineStyle: {
          color: '#DCDFE6'
        }
      },
      axisLabel: {
        color: '#606266'
      }
    },
    yAxis: {
      type: 'value',
      name: '完成百分比',
      nameTextStyle: {
        padding: [0, 0, 0, 40]
      },
      axisLabel: {
        formatter: '{value}%',
        color: '#606266'
      },
      splitLine: {
        lineStyle: {
          color: '#EBEEF5',
          type: 'dashed'
        }
      }
    },
    series: [
      {
        name: '计划进度',
        type: 'line',
        data: data.plan,
        smooth: true,
        symbol: 'emptyCircle',
        symbolSize: 8,
        lineStyle: {
          width: 3
        }
      },
      {
        name: '实际进度',
        type: 'line',
        data: data.actual,
        smooth: true,
        symbol: 'circle',
        symbolSize: 8,
        lineStyle: {
          width: 3
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: 'rgba(103, 194, 58, 0.3)'
              },
              {
                offset: 1,
                color: 'rgba(103, 194, 58, 0)'
              }
            ]
          }
        }
      }
    ]
  }
  
  chartInstance.setOption(option)
}

const handleResize = () => {
  if (chartInstance) {
    chartInstance.resize()
  }
}

watch(timeRange, updateChart)
watch(selectedProject, updateChart)

onMounted(() => {
  initChart()
  window.addEventListener('resize', handleResize)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize)
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }
})
</script>

<style lang="scss" scoped>
.tracking-container {
  padding: 20px;
  
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px solid #EBEEF5;
    
    .page-title {
      margin: 0;
      font-size: 22px;
      font-weight: 600;
      color: #303133;
    }
    
    .summary-stats {
      display: flex;
      gap: 30px;
      
      .stat-item {
        text-align: center;
        padding: 0 10px;
        
        .stat-value {
          display: block;
          font-size: 24px;
          font-weight: bold;
          color: #409EFF;
          
          &.warning {
            color: #E6A23C;
          }
          
          &.danger {
            color: #F56C6C;
          }
        }
        
        .stat-label {
          font-size: 14px;
          color: #606266;
        }
      }
    }
  }
  
  .card {
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
    margin-bottom: 0;
    
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 15px 20px;
      border-bottom: 1px solid #EBEEF5;
      
      .header-title {
        display: flex;
        align-items: center;
        gap: 8px;
        font-size: 16px;
        font-weight: 500;
        color: #303133;
        
        .el-icon {
          font-size: 18px;
          color: #909399;
        }
      }
      
      .header-actions {
        display: flex;
        align-items: center;
        gap: 10px;
      }
    }
  }
  
  .mt-20 {
    margin-top: 20px;
  }
  
  .chart-container {
    padding: 20px;
  }
  
  .filter-select {
    width: 140px;
    margin-left: 10px;
  }
  
  .project-list {
    padding: 5px;
    
    .project-item {
      padding: 12px 15px;
      background-color: #f9f9f9;
      border-radius: 4px;
      margin-bottom: 12px;
      cursor: pointer;
      transition: all 0.3s;
      border-left: 3px solid transparent;
      
      &:hover {
        background-color: #f0f6ff;
      }
      
      &.project-selected {
        background-color: #ecf5ff;
        border-left-color: #409EFF;
      }
      
      .project-info {
        margin-bottom: 10px;
        
        .project-name {
          font-weight: 500;
          font-size: 14px;
          color: #303133;
          margin-bottom: 6px;
        }
        
        .project-meta {
          display: flex;
          justify-content: space-between;
          font-size: 12px;
          color: #909399;
        }
      }
      
      .project-progress {
        .progress-header {
          display: flex;
          justify-content: space-between;
          font-size: 12px;
          margin-bottom: 5px;
          color: #606266;
        }
      }
    }
  }
  
  .resource-list {
    padding: 15px;
    
    .resource-item {
      margin-bottom: 18px;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .resource-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 8px;
        
        .resource-title {
          display: flex;
          align-items: center;
          gap: 8px;
          
          .resource-name {
            font-weight: 500;
            color: #303133;
          }
        }
        
        .resource-usage {
          font-weight: 500;
          color: #303133;
        }
      }
    }
  }
  
  .warning-list {
    padding: 5px 10px;
    
    .warning-item {
      padding: 8px 0;
      
      &.warning-processed {
        opacity: 0.7;
      }
      
      .warning-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 6px;
        
        h4 {
          margin: 0;
          font-size: 14px;
          font-weight: 500;
          color: #303133;
        }
      }
      
      .warning-content {
        margin: 0;
        color: #606266;
        font-size: 13px;
        line-height: 1.5;
      }
      
      .warning-actions {
        margin-top: 10px;
        text-align: right;
      }
    }
  }
  
  .delayed-tasks {
    padding: 10px 0;
  }
  
  .text-success {
    color: #67C23A;
  }
  
  .text-warning {
    color: #E6A23C;
  }
  
  .text-danger {
    color: #F56C6C;
  }
}
</style> 